const app = getApp();
var tcity = require("../../../utils/citys.js");
var API = require("../../../api/api.js");
var event = require("../../../event/event.js");
var utils = require("../../../utils/utils.js");

var isEdit;
let windowHeight;

Page({

  /**
   * page init
   */
  data: {
    areaSelectedStr: '请选择区域',
    areaSelectedStrType: false,
    provinces: [],
    provincesCodes: [],
    province: "",
    provinceCode: "",
    citys: [],
    citysCodes: [],
    city: "",
    cityCode: "",
    districts: [],
    districtsCodes: [],
    district: '',
    districtCode: "",
    value: [0, 0, 0],
    values: [0, 0, 0],
    condition: false,
    provinceID: '',
    detail: "",
    name: "",
    phone: "",
    addrId: "",
    showModalStatus: false,
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!utils.isEmpty(options.curAddr)) {
      isEdit = true;
      wx.setNavigationBarTitle({
        title: '编辑地址'
      })
      var addr = JSON.parse(options.curAddr);
      console.log("edit addr=" + options.curAddr);
      if (addr.address_id) {
        this.setData({
          addrId: addr.address_id,
          province: addr.province,
          provinceCode: addr.province_code,
          city: addr.city,
          user_id: addr.user_id,
          cityCode: addr.city_code,
          district: addr.district,
          districtCode: addr.district_code,
          detail: addr.detail,
          name: addr.recv_username,
          phone: addr.recv_mobile_number,
          areaSelectedStr: addr.province + " " + addr.city + " " + addr.district,
          areaSelectedStrType: true
        });
      } else {
        this.setData({
          province: addr.province_name,
          provinceCode: addr.province_code,
          city: addr.city_name,
          cityCode: addr.city_code,
          district: addr.district_name,
          districtCode: addr.district_code,
          detail: addr.detail,
          user_id: addr.user_id,
          name: addr.name,
          phone: addr.phone,
          areaSelectedStr: addr.province_name + " " + addr.city_name + " " + addr.district_name,
          areaSelectedStrType: true
        });
      }

      console.log("onLoad name =" + addr.name);
    }
    console.log(options)
    // idArr商品新建
    if (options.idArr) {
      this.data.commodity_idArr = options.idArr.split(",")
    }


    var that = this;
    tcity.init(that);
    var cityData = that.data.cityData;
    const provinces = [];
    const provincesCodes = [];
    const citys = [];
    const citysCodes = [];
    const districts = [];
    const districtsCodes = [];

    for (let i = 0; i < cityData.length; i++) {
      provinces.push(cityData[i].name);
      provincesCodes.push(cityData[i].code);
    }

    console.log('province load over!');
    for (let i = 0; i < cityData[0].sub.length; i++) {
      citys.push(cityData[0].sub[i].name);
      citysCodes.push(cityData[0].sub[i].code)
    }
    console.log('city load over!');
    for (let i = 0; i < cityData[0].sub[0].sub.length; i++) {
      districts.push(cityData[0].sub[0].sub[i].name);
      districtsCodes.push(cityData[0].sub[0].sub[i].code);
    }

    that.setData({
      'provinces': provinces,
      "provincesCodes": provincesCodes,
      'citys': citys,
      "citysCodes": citysCodes,
      'districts': districts,
      "districtsCodes": districtsCodes,
      'province': cityData[0].name,
      'city': cityData[0].sub[0].name,
      'district': cityData[0].sub[0].sub[0].name,
      provinceCode: provincesCodes[0],
      cityCode: citysCodes[0],
      districtCode: districtsCodes[0]

    })

    console.log('init data over!');
  },
  /**
     *  pick-view change listen
     */
  bindChange: function (e) {

    var val = e.detail.value
    var t = this.data.values;

    var cityData = this.data.cityData;

    if (val[0] != t[0]) {
      console.log('province no ');
      const citys = [];
      const citysCodes = [];
      const districts = [];
      const districtsCodes = [];

      for (let i = 0; i < cityData[val[0]].sub.length; i++) {
        citys.push(cityData[val[0]].sub[i].name);
        citysCodes.push(cityData[val[0]].sub[i].code);
      }
      for (let i = 0; i < cityData[val[0]].sub[0].sub.length; i++) {
        districts.push(cityData[val[0]].sub[0].sub[i].name);
        districtsCodes.push(cityData[val[0]].sub[0].sub[i].code);
      }

      this.setData({
        province: this.data.provinces[val[0]],
        provinceID: val[0],
        provinceCode: this.data.provincesCodes[val[0]],
        city: cityData[val[0]].sub[0].name,
        cityCode: cityData[val[0]].sub[0].code,
        citys: citys,
        citysCodes: citysCodes,
        district: cityData[val[0]].sub[0].sub[0].name,
        districtCode: cityData[val[0]].sub[0].sub[0].code,
        districts: districts,
        districtsCodes: districtsCodes,
        values: val,
        value: [val[0], 0, 0]
      })

      return;
    }
    if (val[1] != t[1]) {
      console.log('city no');
      const districts = [];
      const districtsCodes = [];
      for (let i = 0; i < cityData[val[0]].sub[val[1]].sub.length; i++) {
        districts.push(cityData[val[0]].sub[val[1]].sub[i].name);
        districtsCodes.push(cityData[val[0]].sub[val[1]].sub[i].code);
      }

      this.setData({
        city: this.data.citys[val[1]],
        cityCode: this.data.citysCodes[val[1]],
        district: cityData[val[0]].sub[val[1]].sub[0].name,
        districtCode: cityData[val[0]].sub[val[1]].sub[0].code,
        districts: districts,
        districtsCodes: districtsCodes,
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      console.log('districts no');
      this.setData({
        district: this.data.districts[val[2]],
        districtCode: this.data.districtsCodes[val[2]],
        values: val
      })
      return;
    }


  },
  areaSele: function () {
    console.log("areaSele");
    // this.setData({
    //   condition: !this.data.condition,
    // });
    this.showModal();
  },

  areaSele_cancel: function () {
    this.hideModal();
  },
  /**
   * button sure
   */
  areaSele_sure: function () {
    this.setData({
      condition: false,
      areaSelectedStr: this.data.province + " " + this.data.city + " " + this.data.district,
      areaSelectedStrType: true

    });
    this.hideModal();
  },
  getAddrDetail: function (e) {
    this.setData({
      detail: e.detail.value
    });
  },
  getName: function (e) {
    this.setData({
      name: e.detail.value
    });
  },
  getPhone: function (e) {
    this.setData({
      phone: e.detail.value
    });
  },

  /**
   * save
   */
  submit: function () {
    var that = this;
    if (!that.data.address_id && !isEdit) {
      let newData = {
        "province_code": that.data.provinceCode,
        "city_code": that.data.cityCode,
        "district_code": that.data.districtCode,
        "province_name": that.data.province,
        "city_name": that.data.city,
        "district_name": that.data.district,
        "detail": that.data.detail,
        "phone": that.data.phone,
        "name": that.data.name,
        "address": that.data.province + that.data.city + that.data.district + that.data.detail,
        "detail": that.data.detail,
        "recv_username": that.data.name,
        "recv_mobile_number": that.data.phone,
        "user_id": that.data.user_id
      }
      event.notify("editAddressClient", newData);
      wx.navigateBack()
      return
    }
    if (!that.checkField().checked) {
      wx.showToast({
        title: that.checkField().msg,
        icon: 'none'

      })
      return;
    }
    var action = '';
    var payload = {
      "province_code": that.data.provinceCode,
      "city_code": that.data.cityCode,
      "district_code": that.data.districtCode,
      "detail": that.data.detail,
      "recv_username": that.data.name,
      "recv_mobile_number": that.data.phone
    }
    if (isEdit) {
      action = 'modify_address';
      payload.address_id = that.data.addrId;

    } else {
      action = 'create_address';
      if (that.data.commodity_idArr) { //是购买商品进入的地址 
        payload.commodity_id = that.data.commodity_idArr;
      }
    }
    API.default.api(action, payload, function (data) {
      if (that.data.commodity_idArr) { //是购买商品进入的地址 
        var newData = {
          address_id: data.data.address_id,
          address_status: true,
          city: that.data.city,
          detail: that.data.detail,
          district: that.data.district,
          province: that.data.province,
          recv_mobile_number: that.data.phone,
          recv_username: that.data.name
        };
        event.notify("addr_add_payunfo", newData);
        wx.navigateBack();

      } else { //地址列表新建
        event.notify("addr_add", "");
        wx.navigateBack();

      }
    }, function (e, du) {
    });
  },


  checkField: function () {
    var info = {
      checked: true,
      msg: ""
    }
    if (utils.isEmpty(this.data.provinceCode) || utils.isEmpty(this.data.cityCode) || utils.isEmpty(this.data.districtCode) ||
      utils.isEmpty(this.data.detail) || utils.isEmpty(this.data.name)) {
      info.checked = false;
      info.msg = "请补全完整信息";
      return info;
    };
    if (!utils.isTel(this.data.phone)) {
      info.checked = false;
      info.msg = "请输入正确的手机号";
      return info;
    }
    return info

  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.getSystemInfo({
      success: function (res) {
        windowHeight = res.windowHeight;
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    isEdit = false;
  },

  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 50,
      timingFunction: "linear",
      delay: 0
    })
    animation.translateY(windowHeight).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 50,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation;
    animation.translateY(windowHeight).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200);

  },
})